import pandas as pd
from tabulate import tabulate
from functools import wraps
import logging
import atexit  # 导入 atexit 模块

logging.basicConfig(level=logging.INFO)
log = logging.getLogger("Handler")


class FindElementLogger:
    def __init__(self, headers=None):
        # 初始化错误信息列表
        if headers is None:
            headers = ['Type', 'Method', 'Element']
        self.logs = [headers]

        # 注册程序退出时调用的函数
        atexit.register(self.display_errors)

    def log_error(self, log_info):
        # 记录单个错误
        self.logs.append(log_info)

    def log_success(self, log_info):
        # 记录单个错误
        self.logs.append(log_info)

    @staticmethod
    def set_find_element(find_type, find_method, desc):
        return [find_type, find_method, desc]

    def display_errors(self):
        # 显示所有错误信息
        if not self.logs:
            print("No logs logged.")
            return

        # 将错误信息转换为 DataFrame
        error_df = pd.DataFrame(self.logs)

        # 使用 tabulate 显示带框的表格
        print(tabulate(error_df, headers='firstrow', tablefmt='grid'))
        log.info(tabulate(error_df, headers='firstrow', tablefmt='grid'))

    def handle_exception(self, func):
        # 捕获异常并记录
        @wraps(func)
        def wrapper(*args, **kwargs):
            try:
                # Check if the method si static (no 'self' argument expected)
                if isinstance(func, staticmethod):
                    # Static method: don't pass 'self'
                    result = func()
                else:
                    result = func(*args, **kwargs)

                print(args)
                self.log_success(self.set_find_element(find_type=func.__name__, find_method=args[1][0], desc=args[1][1]))
                return result
            except Exception as e:
                self.log_error(self.set_find_element(find_type=type(e).__name__, find_method='错误', desc=str(e)))
                # print(e.args)
                # raise e  # 重新抛出异常以确保函数行为不变
                return None

        return wrapper

    @staticmethod
    def log_errors_decorator(cls):

        result = cls

        return result

# error_logger = ErrorLogger()
#
#
# @error_logger.log_errors_decorator
# class ExampleClass:
#
#     @staticmethod
#     @error_logger.handle_exception
#     def divide_by_zero():
#         """This method will cause a divide-by-zero error"""
#         result = 10 / 0  # Division by zero
#
#
# ExampleClass().divide_by_zero()
